import psycopg2
import threading
from config.config import config_params

db_from_config_params = {k: v for k, v in config_params.items() if k.startswith('db_')}
db_params = {
    'host': db_from_config_params['db_host'],
    'port': db_from_config_params['db_port'],
    'database': db_from_config_params['db_database'],
    'user': db_from_config_params['db_user'],
    'password': db_from_config_params['db_password'],
}

# 初始化线程锁
_conn_lock = threading.Lock()
_cursor_lock = threading.Lock()

# 自定义字典记录锁名
lock_names = {
    _conn_lock: 'get_conn_lock',
    _cursor_lock: 'get_cursor_lock'
}

# 私有变量
__conn = None
__cursor = None


def get_conn():
    global __conn
    if __conn is not None:
        return __conn
    #print('Attempting to acquire the lock: ' + lock_names[_conn_lock])
    with _conn_lock:
        #print('Successfully acquired the lock: ' + lock_names[_conn_lock])
        if __conn is None:
            __conn = psycopg2.connect(**db_params)
        #print('Preparing to release the lock: ' + lock_names[_conn_lock])
    #print('The lock: ' + lock_names[_conn_lock] + ' has been released')
    return __conn


def get_cursor():
    global __cursor
    if __cursor is not None:
        return __cursor
    #print('Attempting to acquire the lock: ' + lock_names[_cursor_lock])
    with _cursor_lock:
        #print('Successfully acquired the lock: ' + lock_names[_cursor_lock])
        if __cursor is None:
            __conn = get_conn()
            __cursor = __conn.cursor()
        #print('Preparing to release the lock: ' + lock_names[_cursor_lock])
    #print('The lock: ' + lock_names[_cursor_lock] + ' has been released')
    return __cursor


def close_conn_and_cursor():
    global __conn, __cursor
    if __cursor:
        __cursor.close()
        __cursor = None
    if __conn:
        __conn.close()
        __conn = None



